package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.protocol.RequestContent;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter  extends ZuulFilter {
    //指定过滤器类型
    @Override
    public String filterType() {

        return FilterConstants.PRE_TYPE;
    }
 //指定过滤器添加的位置序号
    @Override
    public int filterOrder() {
        return   6;
    }
// 判断针对当前这次请求，是否要执行过滤代码
    //如果请求item-service 执行权限判断
    //如果请求其他  直接放行
    @Override
    public boolean shouldFilter() {
    // 获得正在调用的服务的服务id
        RequestContext ctx=RequestContext.getCurrentContext();
        String serviceId   =  (String)  ctx.get(FilterConstants.SERVICE_ID_KEY);



        return "item-service".equalsIgnoreCase(serviceId);
    }

//过滤代码
    @Override
    public Object run() throws ZuulException {
        // http://localhost:3001/item-service/5s5s?token=u45t34

        // 得到request对象
   RequestContext  ctx   =RequestContext.getCurrentContext();
  HttpServletRequest request  =  ctx.getRequest();


       // 接收token 参数
       String token  = request.getParameter("token");

  //如果 token 参数不存在，阻止继续调用，直接返回提示

   if(StringUtils.isBlank(token)){

       //阻止继续访问
       ctx.setSendZuulResponse(false);
       //返回登录提示
          String json= JsonResult.err().code(JsonResult.NOT_LOGIN).msg("not  login").toString();

   ctx.addZuulResponseHeader("Content-Type","application/json");

   ctx.setResponseBody(json);

   }

       return null;




    }
}
